/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import ejb.ScoreFacadeRemote;
import ejb.Score;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author automne
 */
public class ScoreControl {
    InitialContext context;
    ScoreFacadeRemote facade;

    public ScoreControl(String mappedName) {
        System.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
        try {
            context = new InitialContext();
            facade = (ScoreFacadeRemote) context.lookup(mappedName);
        } catch (NamingException ex) {
            Logger.getLogger(WordlistControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void register(String username) {
            Score newScore = new Score();
            newScore.setId(username);
            newScore.setLastScore(0);
            newScore.setTotalScore(0);
            newScore.setHighestScore(0);
            facade.create(newScore);
    }

    public void update(String username,int currentScore) {
        Score newScore = facade.find(username);
        if (newScore == null) { 
            newScore = new Score();
            newScore.setId(username);
            newScore.setLastScore(currentScore);
            newScore.setTotalScore(currentScore);
            newScore.setHighestScore(currentScore);
            facade.create(newScore);
        } else {
            newScore.setLastScore(currentScore);
            newScore.setTotalScore(newScore.getTotalScore() + currentScore);
            newScore.setHighestScore(newScore.getHighestScore() > currentScore? newScore.getHighestScore() : currentScore);
            facade.edit(newScore);
        }
    }

    public List<Score> DisplayHighestScore() {
        return facade.orderByHighestScore();
    }

    public List<Score> DisplayTotalScore() {
        return facade.orderByTotalScore();
    }

    public Score getScoreInfo(String username) {
        return facade.find(username);
    }

}
